package com.UnionPayCenter.controller;

import com.UnionPayCenter.ali.manager.AliManager;
import com.UnionPayCenter.ali.request.AliLoginRequest;
import com.UnionPayCenter.distribution.dto.DistributionBaseDTO;
import com.UnionPayCenter.distribution.vo.DistributionTemplateVO;
import com.UnionPayCenter.entity.ChannelEntity;
import com.UnionPayCenter.entity.ResponseWrapper;
import com.UnionPayCenter.enums.ErrorCodeEnum;
import com.UnionPayCenter.exception.ApiException;
import com.UnionPayCenter.jwt.CurrentManager;
import com.UnionPayCenter.jwt.CurrentShop;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.CertAlipayRequest;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.response.AlipaySystemOauthTokenResponse;
import com.alipay.api.response.AlipayUserInfoShareResponse;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.io.FileNotFoundException;
import java.util.Objects;

/**
 * @author noah
 * @since 1.0.0, 2019/09/09
 */
@Slf4j
@Api(value = "alipay", tags = "支付宝小程序")
@RestController
@RequestMapping("/ali")
public class AlipayController {

    @Autowired
    AliManager aliManager;

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ApiOperation(tags = "支付宝登录", httpMethod = "POST", value = "[前台]支付宝用户登录", response = String.class)
    public ResponseWrapper aliLogin(
            @ApiParam(value = "用户code") @RequestBody AliLoginRequest aliLoginRequest) {
        try {
            AlipayUserInfoShareResponse shareResponse = null;
            AlipaySystemOauthTokenResponse response= aliManager.outhToken(aliLoginRequest.getAuthCode());
            if(Objects.nonNull(response)){
                 shareResponse= aliManager.getAliUserInfo(response.getAccessToken());
            }
            return ResponseWrapper.succeed(shareResponse);
        } catch (ApiException e) {
            log.error(String.format("[前台]查询支付宝用户信息失败，参数:%s, 错误信息:%s", JSONObject.toJSONString(aliLoginRequest), e.getMessage()));
            return ResponseWrapper.failed(e.getCode(), e.getMessage());
        } catch (Exception e) {
            log.error(String.format("[前台]查询支付宝用户信息失败，参数:%s, 错误信息:%s", JSONObject.toJSONString(aliLoginRequest), e.getMessage()));
            return ResponseWrapper.failed(ErrorCodeEnum.FL500);
        }
    }


}
